package com.yeswater.multithread.chapter3.test3_1.test4;

import com.yeswater.multithread.chapter2.test2_2.test2.ObjService;
import org.junit.Test;

import java.util.stream.Stream;

/**
 * author : yeswater
 * date : 2023/10/22
 */

public class Main {

    @Test
    public void test1() {
        String s = new String("");
        try {
            // 没有获取锁 会抛出异常
            s.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 只有 wait() 会一直等待
    @Test
    public void test2() {
        String lock = new String("");
        System.out.println("before sync");
        synchronized (lock) {
            System.out.println("first line of sync");
            try {
                lock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("under wait");
        }
    }

    public static void main(String[] args) {
        Object lock = new Object();

        Thread1 thread1 = new Thread1(lock);
        thread1.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread2 thread2 = new Thread2(lock);
        thread2.start();
    }

    @Test
    public void test3() {

    }

    private static class Thread1 extends Thread {
        private Object lock;

        public Thread1(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                synchronized (lock) {
                    System.out.println("sta  ==>> wait   time=" + System.currentTimeMillis());
                    lock.wait();
                    System.out.println("end  ==>> wait   time=" + System.currentTimeMillis());
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static class Thread2 extends Thread {
        private Object lock;

        public Thread2(Object lock) {
            this.lock = lock;
        }

        @Override
        public void run() {
            synchronized (lock) {
                System.out.println("sta  ==>> notify time=" + System.currentTimeMillis());
                lock.notify();
                System.out.println("end  ==>> notify time=" + System.currentTimeMillis());
            }
        }
    }
}
